package internal

import (
	"fmt"
	"encoding/json"
	"GoServer/database"
	"GoServer/user"
	"GoServer/msgbackend"
	"github.com/name5566/leaf/gate"
)

var agentsAll = make(map[gate.Agent]struct{}) //管理连接

func init() {
	skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
	skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
}

func rpcNewAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	_ = a
	agentsAll[a] = struct{}{}
}

func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	_ = a
	Username := user.GetSocketUser(a)
	sendServerClose(Username)
	user.DelSocketUser(a)
	user.UserInfoCacheDELETE(Username)

	delete(agentsAll, a)
}

//发送连接断开消息
func sendServerClose(Username string) {
	fmt.Println("syg send close network: v%",Username)
	g_JsonConfig := database.G_JsonConfig
	ToserverTopic := g_JsonConfig.PrivatetopicAll.Gategetserver
	mapMsg := make(map[string]interface{})
	if Username != "" {
		mapMsg["MsgType"] = "MSG_DISCONNECT"
		mapMsg["MsgData"] = ""
		mapMsg["userName"] = Username
		getTime := msgbackend.GetTime()
		mapMsg["SendTime"] = getTime
		mapMsg["Sender"] = ToserverTopic
		jsonBytes, err := json.Marshal(&mapMsg)
		if err != nil {

		} else {
			fmt.Println(string(jsonBytes))
			msgbackend.MsgRouterWriter(string(jsonBytes))
		}
	}


}
